package com.syni.mdd.yhd.common.all.service;

import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsUserVideoLikeDao;
import com.syni.mdd.yhd.common.all.entity.BmsDxNews;
import com.syni.mdd.yhd.common.all.entity.BmsUserVideo;
import com.syni.mdd.yhd.common.all.entity.BmsUserVideoLike;
import com.syni.mdd.yhd.common.all.entity.BmsVideo;
import com.syni.mdd.yhd.common.all.listen.video.VideoEvent;
import com.syni.mdd.yhd.common.all.service.impl.BaseService;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.yhd.common.all.utils.SpecificationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @className BmsUserVideoLikeService
 * @description 用户与商家点赞
 * Author cfx
 * @DATE 2019/4/8 9:42
 * @VERSION 1.0
 **/

@Service
public class BmsUserVideoLikeService extends BaseService<BmsUserVideoLike, Integer> {

    @Autowired
    BmsUserVideoLikeDao bmsUserVideoLikeDao;

    @Autowired
    BmsVideoService bmsVideoService;

    @Autowired
    BmsDxNewsService bmsDxNewsService;

    @Autowired
    BmsUserVideoService bmsUserVideoService;

    @Autowired
    RedisTemplate redisTemplate;

    public BmsUserVideoLikeDao getBaseDao() {
        return bmsUserVideoLikeDao;
    }

    @Transactional
    public Map<String,Object> operationLike(Integer userId, Integer videoId) {
        final Integer add = 1;
        final Integer subduction = -1;
        Optional<BmsVideo> bmsVideoOptional = bmsVideoService.getBaseDao().findById(videoId);
        if(!bmsVideoOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_VIDEO_NO_EXIST,"视频不存在");
        }
        BmsVideo bmsVideo = bmsVideoOptional.get();
        List<BmsUserVideoLike> bmsUserVideoLikes = bmsUserVideoLikeDao.findByBmsUserIdAndBmsVideoId(userId, videoId);
        Map<String,Object> userData = new HashMap<>();
        BmsUserVideoLike bmsUserVideoLike;
        if (!(bmsUserVideoLikes != null && bmsUserVideoLikes.size() > 0)) {
            bmsUserVideoLike = new BmsUserVideoLike();
            bmsUserVideoLike.setBmsUserId(userId);
            bmsUserVideoLike.setBmsVideoId(videoId);
            bmsUserVideoLike.setLikeTime(new Date());
            bmsUserVideoLikeDao.save(bmsUserVideoLike);
            if(bmsUserVideoLike.getId() != null) {
                //加入消息通知表
                addToBmsDxNews(userId, bmsVideo);
                //加入redis
                addUserLikeToRedis(videoId, add);
                userData.put("likeOrCanelLike",Constants.COMMON_FLAG_TRUE_INT);
                userData.put("likeNum",bmsVideoService.getVideoNowLike(videoId));
                return ResultMapHelper.success(userData,"点赞成功");
            }
        } else {
            bmsUserVideoLike = bmsUserVideoLikes.get(0);
            bmsUserVideoLikeDao.delete(bmsUserVideoLike);
            if(!bmsUserVideoLikeDao.existsById(bmsUserVideoLike.getId())) {
                removeToBmsDxNews(userId, videoId);
                addUserLikeToRedis(videoId, subduction);
                userData.put("likeOrCanelLike",Constants.COMMON_FLAG_FALSE_INT);
                userData.put("likeNum",bmsVideoService.getVideoNowLike(videoId));
                return ResultMapHelper.success(userData,"取消点赞成功");
            }
        }
        return ResultMapHelper.failure(ResultMsg.ADMIN_ERROR);
    }

    /**
     * @Description 推送到消息通知表（极光推送）
     * @Author: cfx
     * @Date: 2019/8/13
     */
    public void addToBmsDxNews(Integer userId,BmsVideo bmsVideo){
        BmsCommonService.getApplicationContext().publishEvent(new VideoEvent("videoLike",bmsVideo,userId));
    }

    public void removeToBmsDxNews(Integer userId,Integer videoId){
        //先查询该视频是否还有其他人点赞
        Map<String,Object> videoLikeMap = bmsUserVideoLikeDao.selfFindBmsVideoIdExist(videoId);
        if(videoLikeMap.size() == 0){
            //删除这条消息
            BmsDxNews bmsDxNews = bmsDxNewsService.getBaseDao().findByBmsVideoIdAndParentTypeAndChildType(videoId,
                    BmsDxNewsService.PARENTTYPT_INT,BmsDxNewsService.PARENTTYPT_INT_LIKE);
            if(bmsDxNews != null){
                bmsDxNewsService.delete(bmsDxNews);
            }
        }
    }

    public void addUserLikeToRedis(Integer videoId,Integer status) {
        redisTemplate.opsForZSet().incrementScore(Constants.REDIS_KEY_LIKEDK,"like:" + videoId,status);
    }

    /*public List<BmsVideo> getList(Integer user_id, Integer page) {
        List<BmsVideo> bmsVideoList = new LinkedList<>();
        Integer pageSize = 9;
        PageRequest pageRequest = PageRequest.of(page - 1,pageSize, Sort.Direction.DESC,"likeTime");
        List<BmsUserVideoLike> bmsUserVideoLikes = bmsUserVideoLikeDao.findByBmsUserId(user_id,pageRequest);
        if(bmsUserVideoLikes != null && bmsUserVideoLikes.size() > 0){
            for(BmsUserVideoLike bmsUserVideoLike : bmsUserVideoLikes){
                BmsVideo bmsVideo = bmsUserVideoLike.getBmsVideo();
                bmsVideoList.add(bmsVideo);
            }
        }
        return bmsVideoList;
    }*/

    public List<BmsVideo> getListToFront(Integer userId, String latitude, String longitude,
                                         Integer pageNum,Integer pageSize,String myUserId) {
        List<BmsVideo> bmsVideoList = new LinkedList<>();
        //查询点赞最新，且没有被删除的视频
        List<BmsUserVideoLike> bmsUserVideoLikes = this.getList(userId,pageNum,pageSize);
        if(bmsUserVideoLikes != null && bmsUserVideoLikes.size() > 0){
            for(BmsUserVideoLike bmsUserVideoLike : bmsUserVideoLikes){
                BmsVideo bmsVideo = bmsUserVideoLike.getBmsVideo();
               /* if(bmsVideo.getIsDelete() != null && bmsVideo.getIsDelete() == Constants.COMMON_FLAG_TRUE_INT){
                    continue;
                }*/
                bmsVideoList.add(bmsVideo);
            }
        }
        Set videoIds = bmsVideoService.getVideoIds(bmsVideoList);
        bmsVideoService.findVideoBussess(bmsVideoList);
        bmsVideoService.calculatedDistance(bmsVideoList, latitude, longitude);
        bmsVideoService.setUserLikeAndFoot(myUserId,bmsVideoList,videoIds);
        bmsVideoService.setVideoStatic(bmsVideoList);
        bmsVideoService.setVideoComment(bmsVideoList,videoIds);
        bmsVideoService.setSendMes(bmsVideoList,videoIds);
        return bmsVideoList;
    }

    public List<BmsUserVideoLike> getList(Integer userId,Integer pageNum,Integer pageSize){
        List<BmsUserVideoLike> bmsUserVideoLikes;
        if(pageNum != null && pageSize != null){
            Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"like_time");
            bmsUserVideoLikes = bmsUserVideoLikeDao.findByBmsUserId(userId,pageable);
        }else {
            Sort sort = Sort.by(Sort.Direction.DESC,"likeTime");
            bmsUserVideoLikes = bmsUserVideoLikeDao.findByBmsUserId(userId,sort);
        }
        return bmsUserVideoLikes;
    }

    /**
     * @Description 通过userId,和video集合查找
     * @Author cfx
     * @Date 2019/7/8
     */
    public List<BmsUserVideoLike> getListByUserIdAndVideoId(Integer userId,Set videoId){
        List<BmsUserVideoLike> likeList = bmsUserVideoLikeDao.findByBmsUserIdAndBmsVideoIdIsIn(userId,videoId);
        return likeList;
    }

    public List<Map<String,Object>> getByUserIdAndVideoIdIn(Integer userId,Set videoId){
        List<Map<String,Object>> likeList = bmsUserVideoLikeDao.selfFindByUserIdAndVideoIds(userId,videoId);
        return likeList;
    }

    public Integer findUserTotalLike(Integer userId) {
        Integer ret = 0;
        Map<String,Object> resultMap = bmsUserVideoLikeDao.selfCountUserLikeNum(userId);
        if(resultMap != null && resultMap.size() > 0){
            ret = Integer.parseInt(resultMap.get("num").toString());
        }
        return ret;
    }

    /**
     * @Description 查询用户获赞数
     * @Param Integer
     * @return Integer
     * @Author: cfx
     * @Date: 2019/8/5
     */
    public Integer getMyGetLikeNum(Integer userId) {
        //查询用户发布的视频
        Integer userGetLikeNum = 0;
        List<BmsUserVideo> bmsUserVideos = bmsUserVideoService.getByUserId(userId);
        if(bmsUserVideos != null && bmsUserVideos.size() > 0){
            Set<Integer> videoIds = new HashSet<>();
            for(BmsUserVideo bmsUserVideo : bmsUserVideos){
                videoIds.add(bmsUserVideo.getBmsVideoId());
            }
            //查询用户发布的视频
            Map<String,Object> conditionMap = new HashMap<>();
            conditionMap.put("id_IN",videoIds);
            conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
            conditionMap.put("fromOrigin",Constants.USER_CLIENT);
            List<BmsVideo> bmsVideos = bmsVideoService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
            videoIds.clear();
            if(bmsVideos != null && bmsVideos.size() > 0){
                for(BmsVideo bmsVideo : bmsVideos){
                    videoIds.add(bmsVideo.getId());
                }
            }
            if(videoIds.size() > 0){
                conditionMap.clear();
                conditionMap.put("bmsVideoId_IN",videoIds);
                Long countNum = bmsUserVideoLikeDao.count(new SpecificationUtils(conditionMap));
                userGetLikeNum = countNum.intValue();
            }
        }
        return userGetLikeNum;
    }
}
